import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Button, Select, Upload, Icon, message, Spin, Row, Col } from 'antd';
import _ from 'lodash';
import { router, withRouter } from 'umi';
import RichText from '@/components/RichText';
import { BottomAction } from '@/components';
import { eventTrack } from '@/utils/track';
import { formatEmployee } from './utils';
import { useSearchMailList, useMailInfo, useAvatarUrl, useSendMail } from './hooks';
import { Attachment } from './components';
import styles from './styles.less';

const layout = {
    labelCol: { md: { span: 3 }, lg: { span: 1 } },
    wrapperCol: { md: { span: 21 }, lg: { span: 23 } }
};
const { Option } = Select;

// 发邮件
// TODO 这个页面太赶的时间弄出来，个人觉得后面有时间还是要整理下流程的o(╥﹏╥)o

const MailForm = ({ form, location }) => {
    const { mailId, doType } = location.query;

    const email = localStorage.getItem('currentMail');
    const [uploadFiles, setUploadFiles] = useState([]);
    const [previewList, setPreviewList] = useState([]);

    // 生成图片预览数组
    useEffect(() => {
        setPreviewList([...uploadFiles.map(item => ({ uid: item.uid, fileName: item.name, fileSize: item.size }))]);
    }, [uploadFiles]);

    // 收件人搜索列表
    const [recipValue, setRecipValue] = useState(null);
    const [recipSearchLoading, recipSearchData, setRecipData, setRecipLoading] = useSearchMailList(recipValue);

    // 抄送人列表
    const [copyToValue, setCopyToValue] = useState(null);
    const [copyToSearchLoading, copyToSearchData, setCopyToData, setCopyToLoading] = useSearchMailList(copyToValue);

    // 拉取邮箱详情信息
    const [mailInfoLoading, mailInfoData] = useMailInfo(mailId);

    // 提交表单
    const [sendParams, setSendParams] = useState(null);
    const { loading: sendLoading, isSuccess, resultMsg, method } = useSendMail(sendParams); // 发邮件
    const handleSubmit = () => {
        const { to, cc, subject, content } = form.getFieldsValue();
        const toArr = to && to.map(item => item.key);
        const ccArr = cc && cc.map(item => item.key);

        if (!content || content === '<p></p>') {
            message.error('收件人、主题、正文都不能为空');
            return false;
        }
        let mailContent = content;
        if (_.size(mailInfoData) > 0) {
            if (mailInfoData.htmlContent && _.size(mailInfoData.htmlContent) > 0) {
                mailContent = `${mailContent}<div style="text-align:center;border-top:1px dashed #ccc;border-bottom:1px dashed #ccc;padding:10px;color:#666;">以下为原内容</div>${mailInfoData.htmlContent}`;
            } else if (mailInfoData.content && _.size(mailInfoData.content) > 0) {
                mailContent = `${mailContent}<div style="text-align:center;border-top:1px dashed #ccc;border-bottom:1px dashed #ccc;padding:10px;color:#666;">以下为原内容</div>${mailInfoData.content}`;
            }
        }
        setSendParams({
            to: !_.isEmpty(toArr) ? toArr.join(',') : '',
            cc: !_.isEmpty(ccArr) ? ccArr.join(',') : '',
            subject,
            content: mailContent,
            uploadFiles
        });
        return false;
    };
    useEffect(() => {
        const sendType = doType ? Number(doType) : 4;
        if (isSuccess && !resultMsg) {
            // 埋点
            eventTrack({
                eventName: 'send_button_click',
                eventProps: { send_status: 0, send_type: sendType }
            });
            setTimeout(() => {
                history.push('/personal/message/mails');
            }, 0);
        } else if (!isSuccess && resultMsg) {
            // 埋点
            eventTrack({
                eventName: 'send_button_click',
                eventProps: { send_status: 1, error_info: resultMsg, send_type: sendType }
            });
            method.resetSuccess(); // 失败后初始化下状态以便监听下次状态
        }
    }, [isSuccess, resultMsg]);

    // 删除图片
    const onRemove = e => {
        uploadFiles.splice(
            uploadFiles.findIndex(item => item.uid === e.uid),
            1
        );
        setUploadFiles([...uploadFiles]);
    };

    // 上传参数
    const uploadParam = {
        name: 'file',
        accept: '*',
        className: 'upload-list-inline',
        defaultFileList: [],
        multiple: true,
        showUploadList: false,
        fileList: uploadFiles,
        beforeUpload(file, fileList) {
            for (let i = 0; i < fileList.length; i += 1) {
                const isLimit = file.size / 1024 / 1024 < 30;
                if (!isLimit) {
                    message.error(`文件：${file.name} 超过30MB！`);
                    return false;
                }
            }
            setUploadFiles([...uploadFiles, ...fileList]);
            return false;
        }
    };

    // =========================mailId和doType参数不为空处理逻辑=========================

    // 邮箱详情里面的抄送列表
    const { ccList, receiverList } = mailInfoData;
    let tempReceiverList =
        !_.isEmpty(receiverList) &&
        _.uniq(receiverList.split(',')).map(item => ({ email: item, employeeName: item, key: item }));
    let tempCopyList =
        !_.isEmpty(ccList) && _.uniq(ccList.split(',')).map(item => ({ email: item, employeeName: item, key: item }));
    const doTypeMap = {
        1: {
            // 回复收件人：发件人，不要抄送
            initSelectList: () => {
                form.setFieldsValue({
                    to: [
                        {
                            email: mailInfoData.sender,
                            employeeName: mailInfoData.sender,
                            key: mailInfoData.sender
                        }
                    ],
                    cc: undefined,
                    subject: `回复：${mailInfoData.subject}`
                });
            }
        },
        2: {
            //  回复全部：收件人列表+发件人(排除自己)，抄送(排除自己)
            initSelectList: () => {
                tempReceiverList.unshift({
                    email: mailInfoData.sender,
                    employeeName: mailInfoData.sender,
                    key: mailInfoData.sender
                });
                tempReceiverList = _.pull(
                    tempReceiverList.map(item => {
                        if (item.email.toLowerCase() !== email) {
                            return item;
                        }
                        return '';
                    }),
                    ''
                );
                if (!_.isEmpty(tempCopyList)) {
                    tempCopyList = _.pull(
                        tempCopyList.map(item => {
                            if (item.email.toLowerCase() !== email) {
                                return item;
                            }
                            return '';
                        }),
                        ''
                    );
                }
                form.setFieldsValue({
                    to: tempReceiverList,
                    cc: tempCopyList || undefined,
                    subject: `回复：${mailInfoData.subject}`
                });
            }
        },
        3: {
            // 转发：收件人列表和抄送为空
            initSelectList: () => {
                form.setFieldsValue({
                    to: undefined,
                    cc: undefined,
                    subject: `转发：${mailInfoData.subject}`
                });
            }
        }
    };

    /*
        邮件和头像、姓名不在同一套系统里面，每次要拉取两次数据
        还要处理数据替换的逻辑。。。╮(╯▽╰)╭
    */

    // 邮件列表
    const [mailList, setMailList] = useState([]);

    useEffect(() => {
        if (!_.isEmpty(mailInfoData)) {
            // 通过map给表单写入默认值
            doTypeMap[doType].initSelectList();

            // 读取收件人和抄送人默认邮件生成列表拉取头像
            const arr = _.remove(
                _.uniq([mailInfoData.sender, ...receiverList.split(','), ...ccList.split(',')]),
                v => v !== ''
            );
            setMailList(arr);
        }
    }, [mailInfoData]);

    // 通过邮件列表拉取头像
    const { resData: avatarList } = useAvatarUrl(mailList);

    // 这个主要是处理回复等进来有默认发件人、抄送人的名称同步!!!!吐血N升
    useEffect(() => {
        if (!_.isEmpty(avatarList)) {
            const recarr = receiverList.split(',');
            const ccarr = ccList.split(',');
            recarr.unshift(mailInfoData.sender);
            ccarr.unshift(mailInfoData.sender);

            setRecipData(
                _.compact(
                    _.uniq([
                        ...recarr.map(item => {
                            if (item !== '') {
                                return {
                                    email: item,
                                    key: item,
                                    employeeName: formatEmployee(avatarList, item).name
                                };
                            }
                            return '';
                        })
                    ])
                )
            );
            setCopyToData(
                _.compact(
                    _.uniq([
                        ...ccarr.map(item => {
                            if (item !== '') {
                                return {
                                    email: item,
                                    key: item,
                                    employeeName: formatEmployee(avatarList, item).name
                                };
                            }
                            return '';
                        })
                    ])
                )
            );
        }
    }, [avatarList]);

    //= ================================== end ==================================

    return (
        <Card bordered={false} bodyStyle={{ padding: '0  24px 12px' }} className={styles.mailFormWrap}>
            <Form {...layout} hideRequiredMark labelAlign="left">
                <Form.Item label="收件人：">
                    {form.getFieldDecorator('to')(
                        <Select
                            allowClear
                            mode="tags"
                            autoComplete="off"
                            filterOption={false}
                            labelInValue
                            notFoundContent={recipSearchLoading ? <Spin size="small" /> : null}
                            optionLabelProp="label"
                            onChange={() => {
                                setRecipValue(null);
                                setRecipData([]);
                                setRecipLoading(false);
                            }}
                            onSearch={_.debounce(e => {
                                setRecipData([]);
                                setRecipLoading(true);
                                setRecipValue(e);
                            }, 800)}
                        >
                            {recipSearchData.length > 0 &&
                                recipSearchData.map(item => (
                                    <Option key={item.employeeCode} value={item.email} label={item.employeeName}>
                                        <b>{item.employeeName}</b>
                                        <span style={{ color: '#646464', marginRight: 16 }}></span>
                                        {item.email}
                                    </Option>
                                ))}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="抄&nbsp;&nbsp;&nbsp;送 ：">
                    {form.getFieldDecorator('cc')(
                        <Select
                            allowClear
                            mode="tags"
                            labelInValue
                            autoComplete="off"
                            filterOption={false}
                            notFoundContent={copyToSearchLoading ? <Spin size="small" /> : null}
                            optionLabelProp="label"
                            onChange={() => {
                                setCopyToValue(null);
                                setCopyToData([]);
                                setCopyToLoading(false);
                            }}
                            onSearch={_.debounce(e => {
                                setCopyToData([]);
                                setCopyToLoading(true);
                                setCopyToValue(e);
                            }, 800)}
                        >
                            {copyToSearchData.length > 0 &&
                                copyToSearchData.map(item => (
                                    <Option key={item.employeeCode} value={item.email} label={item.employeeName}>
                                        <b>{item.employeeName}</b>
                                        <span style={{ color: '#646464', marginRight: 16 }}></span>
                                        {item.email}
                                    </Option>
                                ))}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="主&nbsp;&nbsp;&nbsp;题 ：">
                    <Row>
                        <Col span={22}>
                            {form.getFieldDecorator('subject')(<Input autoComplete="off" maxLength={255} />)}
                        </Col>
                        <Col span={2} style={{ lineHeight: '42px', textAlign: 'right' }}>
                            {_.size(form.getFieldValue('subject'))}/255
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item className={styles.normalwrap} style={{ padding: '8px 0', marginBottom: 4 }}>
                    {form.getFieldDecorator('files')(
                        <>
                            <Upload {...uploadParam}>
                                <Button disabled={uploadFiles.length >= 10}>
                                    <Icon type="paper-clip" /> 添加附件
                                </Button>
                            </Upload>
                            <span style={{ fontSize: 12, color: '#F3BA00', margin: '0 17px 0 8px' }}>(最大30MB)</span>
                            <span style={{ color: '#8C8C8C', fontSize: 12 }}>
                                支持扩展名：.rar .zip .doc .docx .pdf .jpg 等
                            </span>
                        </>
                    )}
                    {previewList && previewList.length > 0 && (
                        <div style={{ marginTop: 16 }}>
                            <Attachment attachmentList={previewList} type="del" onClick={onRemove} />
                        </div>
                    )}
                </Form.Item>
                <Form.Item className={styles.normalwrap} style={{ borderBottom: 0 }}>
                    {form.getFieldDecorator('content')(<RichText placeholder="请输入邮件正文" />)}
                </Form.Item>
                {!mailInfoLoading && !_.isEmpty(mailInfoData) && (
                    <iframe
                        title="邮箱内容"
                        src={`/personal/message/mails/mailInfo?mailId=${mailId}`}
                        width="100%"
                        style={{ height: 'calc(100vh - 310px)' }}
                        frameBorder="0"
                    ></iframe>
                )}
                <BottomAction>
                    {/* <Affix offsetBottom={0}> */}

                    <Button
                        onClick={_.debounce(() => {
                            handleSubmit();
                        }, 500)}
                        type="primary"
                        style={{ marginRight: 16 }}
                        loading={sendLoading}
                    >
                        发送
                    </Button>
                    <Button
                        onClick={async () => {
                            // 埋点
                            eventTrack({ eventName: 'cancel_button_click' });
                            await history.push('/personal/message/mails');
                        }}
                    >
                        取消
                    </Button>
                    {/* </Affix> */}
                </BottomAction>
            </Form>
        </Card>
    );
};

export default withRouter(Form.create({ name: 'MailForm' })(MailForm));
